﻿namespace ufida.u9.ait.openapi
{
	using System;
	using System.Collections.Generic;
	using System.Text;
    using ufida.u9.ait.openapi.utils;
    using UFIDA.U9.CBO.Pub.Controller;
    using UFIDA.U9.SM.SC;
    using UFSoft.UBF.AopFrame;
    using UFSoft.UBF.Business;
    using UFSoft.UBF.Util.Context;

	/// <summary>
	/// SaleContractApproveSV partial 
	/// </summary>	
	public partial class SaleContractApproveSV 
	{	
		internal BaseStrategy Select()
		{
			return new SaleContractApproveSVImpementStrategy();	
		}		
	}
	
	#region  implement strategy	
	/// <summary>
	/// Impement Implement
	/// 
	/// </summary>	
	internal partial class SaleContractApproveSVImpementStrategy : BaseStrategy
	{
		public SaleContractApproveSVImpementStrategy() { }

		public override object Do(object obj)
		{						
			SaleContractApproveSV bpObj = (SaleContractApproveSV)obj;
            try
            {
				if (bpObj.Data == null || bpObj.Data.Count == 0)
					throw new Exception("传入参数为空");
				List<CommonArchiveDataDTOData> retlist = new List<CommonArchiveDataDTOData>();

				foreach (var dto in bpObj.Data)
				{
					if (String.IsNullOrEmpty(dto.Code))
						throw new Exception("必须传入单号[Code]");

					SaleContract doc = SaleContract.Finder.Find($"DocNo='{dto.Code}'");
					if (doc == null)
					{
						//新增逻辑
						throw new Exception($"单号:{dto.Code}已经不存在,不能审核!");
					}
					else
					{
						//修改逻辑
						doc = ApproveDoc(doc);
						//返回值
						CommonArchiveDataDTOData ret = new CommonArchiveDataDTOData()
						{
							ID = doc.ID,
							Code = doc.DocNo,
						};
						retlist.Add(ret);
					}
				}

				return ResultUtils.success(bpObj, bpObj.Data, retlist);
			}
			catch(Exception ex)
            {
				return ResultUtils.error(bpObj, bpObj.Data, ex);
			}
		}

		private SaleContract ApproveDoc(SaleContract doc)
		{
			if (doc.Status == SCStatusEnum.Approved)
				throw new Exception($"单号:{doc.DocNo}已经审核,不能再次审核!");

			using (ISession session = Session.Open())
			{
				doc.Status = SCStatusEnum.Approved;
				foreach (var line in doc.SaleContractLines)
				{
					line.Status = SCStatusEnum.Approved;
				}

				session.Commit();
			}

			return doc;
		}
	}

	#endregion
	
	
}